/**
 * Created by Administrator on 2019/1/28.
 */
const Service = require('egg').Service;
const Utils = require('../utils/index');
const yunzhijiaCookieCache = {};
const uploadRecord = require('../utils/store').uploadRecord;

class loginService extends Service {
  async index(userInfo) {
    const { config, ctx } = this;
    const { serverUrl, queryUserUrl } = config.urlConfig;
    // ctx.curl用于发出网络请求
    const finalData = [];
    let opts,
      userId,
      cookie;

    // 表示已经登陆了，session里有
    // if (ctx.session.phone && yunzhijiaCookieCache[userInfo.username]) {
    //   cookie = yunzhijiaCookieCache[userInfo.username];
    // } else {
    opts = {
      method: 'post',
      // contentType: 'application/x-www-form-urlencoded',
      headers: config.headers,
      data: {
        email: userInfo.username,
        password: userInfo.password,
        remember: false,
        forceToNetwork: false,
        redirectUrl: '',
        accountType: '',
      },
      dataType: 'json',
    };

    ctx.session.phone = userInfo.username;
    ctx.session.password = userInfo.password;


    const { headers } = await ctx.curl(`${serverUrl}/rest/user/login?${Date.now()}`, opts);
    // 登陆失败
    if (!headers || !headers['set-cookie']) {
      return { err: '登录失败，请检查用户名或者密码是否正确' };
    }
    const cookieStr = headers['set-cookie'].join(',') || '';
    cookie = Utils.getCookie(cookieStr);
    yunzhijiaCookieCache[userInfo.username] = cookie;

    const teams = await ctx.curl(`${serverUrl}/rest/teamaccount/showteams`, {
      headers: {
        cookie,
      },
      method: 'get',
      dataType: 'json',
    });

    const { name } = teams.data.teams[0];
    const jobNo = teams.data.teams[0].networkProfile.jobNo;
    userId = teams.data.teams[0].userId;
    finalData.name = ctx.session.name = name; // 个人姓名
    finalData.userId = userId;
    const signInfo = await ctx.curl(`${serverUrl}/rest/app/getlightappurl`, {
      headers: {
        cookie,
      },
      timeout: 20 * 1000,
      method: 'get',
      data: {
        appId: '10243',
        originType: 'web',
        '_=': Date.now(),
      },
      dataType: 'json',
    });

    const lightAppUrl = signInfo.data.lightAppUrl;
    const ticket = Utils.urlParam(lightAppUrl).ticket;
    const limit = Utils.getDaysByDateString(userInfo.startDate, userInfo.endDate);
    const header = Object.assign({ cookie }, config.headers);
    const userList = await ctx.curl(queryUserUrl, {
      method: 'get',
      headers: header,
      data: {
        startDate: userInfo.startDate,
        endDate: userInfo.endDate,
        userId,
        status: '',
        page: 1,
        limit,
        sort: '-day',
        lappName: 'attendance',
        ticket,
      },
      dataType: 'json',
    });

    ctx.session.startDate = userInfo.startDate;
    ctx.session.endDate = userInfo.endDate;

    const list = userList.data.data.list;

    list.forEach(data => {
      data.jobNo = jobNo;
      const res = this.filterData(data);
      if (res && res.money !== 0) { // 有钱的再导出
        finalData.push(Object.values(res));
      }
    });

    if (!finalData.length) {
      return { err: '没有加班数据' };
    }

    uploadRecord[name] = { name, phone: userInfo.username};

    return finalData;
  }

  /**
   * startWork: 最早签到时间'07:51 深圳金蝶软件园'
   * endWork: 最晚签到时间 '07:51 深圳金蝶软件园'
   * money: 每天的补贴金额
   * 记钱规则：
   * 1. 周一到周五每天8点后签到并且到岗时长大于8个小时有15块钱
   * 2. 周末签到满2个小时15块, 满四个小时30块。
   * 3. 特殊情况，签到时间超过24点并且小于第二天6点的，工作时长大于8个小时，有15块补贴。（通宵到6点已经够要命的了，应该没有更恐怖的了吧）
   */
  filterData(obj) {
    if (!obj || typeof obj !== 'object' || obj.workLong === 0) return false;

    // 定义一个所需要的字段的对象
    const needFields = {
      department: obj.department,
      jobNo: obj.jobNo,
      userName: obj.userName,
      date: Utils.formatDate(new Date(obj.day), 'yyyy-MM-dd EE'),
      startWork: obj.startWork ? obj.startWork.substr(0, 5) : obj.startWork,
      endWork: obj.endWork ? obj.endWork.substr(0, 5) : obj.endWork,
      workLong: obj.workLong,
      money: 0,
      didi: '', // 滴滴打车
    };

    const isWeekEnd = needFields.date.substr(needFields.date.length - 1) === '六' || needFields.date.substr(needFields.date.length - 1) === '日';

    // 周末的计算规则
    if (isWeekEnd) {
      if (needFields.workLong < 4) {
        needFields.money = 0;
      } else if (needFields.workLong >= 8) {
        needFields.money = 30;
      } else {
        needFields.money = 15;
      }
    } else { // 工作日的计算规则
      const time = needFields.endWork.substr(0, 5).
        split(':');
      const hour = parseInt(time[0]);
      // 超过24点的问题
      if (hour >= 20 || (hour <= 6 && needFields.workLong > 8)) {
        needFields.money = 15;
      } else {
        needFields.money = 0;
      }
    }

    // 是否乘车
    if (isWeekEnd) {
      if (needFields.workLong > 1) {
        needFields.didi = '-';
      }
    } else {
      if ((needFields.workLong >= 11 && Number(needFields.endWork.slice(0, 2)) >= 21) || needFields.workLong >= 13) {
        needFields.didi = '-';
      }
    }

    return needFields;
  }

  isUserEmpty(user) {
    if (!user.username || user.username === '' || !user.password || user.password === '') {
      return true;
    }
    return false;
  }

}

module.exports = loginService;
